package com.heima.juc.unlock;

import com.heima.juc.n2.Sleeper;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicStampedReference;

/**
 * @author : leimingchao
 * @date Date : 2022年02月12日 19:11
 */
@Slf4j(topic = "c.Test3")
public class Test3 {

    static AtomicStampedReference<String> reference = new AtomicStampedReference<>("A",0);

    public static void main(String[] args) {
        log.debug("main start....");
        //获取值 A
        //这个共享变量被其他线程修改过
        String prev = reference.getReference();
        //获取版本号
        int stamp = reference.getStamp();
        log.debug("{}", stamp);
        other();
        Sleeper.sleep(1);
        // 尝试改为 C
        log.debug("{}",reference.getStamp());
        log.debug("change A -> C : {}", reference.compareAndSet(prev,"C", stamp, stamp + 1));
    }

    private static void other() {

        new Thread(() -> {
            int stamp = reference.getStamp();
            log.debug("{}",stamp);
            log.debug("chang A -> B : {}",reference.compareAndSet(reference.getReference(), "B", stamp,stamp + 1));
        },"t1").start();

        Sleeper.sleep(0.5);

        new Thread(() -> {
            int stamp = reference.getStamp();
            log.debug("{}",stamp);
            log.debug("chang B -> A : {}",reference.compareAndSet(reference.getReference(), "A", stamp, stamp + 1));
        },"t2").start();
    }
}
